package com.xinke.edu.mypetadoption.fragment.Home.adpter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.chad.library.adapter4.BaseQuickAdapter;
import com.chad.library.adapter4.viewholder.QuickViewHolder;
import com.xinke.edu.mypetadoption.Activity.adapter.ShoppingCartAdapter;
import com.xinke.edu.mypetadoption.R;
import com.xinke.edu.mypetadoption.entity.Product;
import com.xinke.edu.mypetadoption.util.DensityUtil;
import com.xinke.edu.mypetadoption.util.ShoppingCartManager;

public class ProductAdpter extends BaseQuickAdapter<Product, QuickViewHolder> {
    @Override
    protected void onBindViewHolder(@NonNull QuickViewHolder quickViewHolder, int i, @Nullable Product product) {
        if (product == null) return;
        
        ImageView img = quickViewHolder.getView(R.id.img);
        // 优化Glide图片加载，添加占位图、错误图、尺寸限制和内存缓存
        Glide.with(getContext())
             .load(product.getCoverImage())
             .placeholder(R.mipmap.ic_launcher) // 占位图
             .error(R.mipmap.ic_launcher)       // 错误图
             .override(200, 200)                // 限制图片尺寸
             .skipMemoryCache(false)            // 启用内存缓存
             .into(img);
        quickViewHolder.setText(R.id.name, product.getName());
        quickViewHolder.setText(R.id.price, "￥" + product.getPrice());
        
        // 获取加入购物车按钮（实际是TextView）
        TextView addToCartButton = quickViewHolder.getView(R.id.add_to_cart);
        // 设置加入购物车按钮的点击事件
        addToCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 将商品添加到购物车
                ShoppingCartManager.getInstance().addItem(
                    product.getName(),
                    product.getPrice().doubleValue(),
                    1,  // 默认添加数量为1
                    product.getCoverImage(),
                    (product.getId() != null) ? product.getId().intValue() : 0
                );
                // 显示添加成功提示
                Toast.makeText(getContext(), "已加入购物车", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @NonNull
    @Override
    protected QuickViewHolder onCreateViewHolder(@NonNull Context context, @NonNull ViewGroup viewGroup, int i) {
        return new QuickViewHolder(R.layout.item_product,viewGroup);
    }
}
